<template>
  <zb-ai-result-top v-if="!isMobile" :detail="detail" />
  <!-- answerStatus 当前按钮状态 0-无发送内容， 1-回答中 2-回答结束 3-中断回答  {{curLink.isSend}} {{curLink.status}}-->
  <div class="content flex">
    <div class="flex-1 talk-con relative w-100">
      <zb-scroll ref="zbScrollRef">
        <zb-ai-result-top v-if="isMobile" :detail="detail" />
        <span v-if="answerStatus == 0" class="form-tips">生成的内容显示在这里...</span>
        <zb-ai-loading v-else-if="answerStatus == 1 && markdownHTML.length === 0" />
        <zb-markdown v-else :content="markdownHTML" :ing="printEnd == 1" />
      </zb-scroll>
    </div>
    <zb-ai-result-history />
    <zb-ai-btn v-if="answerStatus != 0" @again="sendMsgFun(sendContent)" @stop="stopTalk" :content="markdownHTML" :ing="answerStatus" :again="againLink" />
    <!-- 声音 -->
    <zb-ai-audio ref="audioRef" />
  </div>
</template>
<script lang="ts" setup>
import { nextTick, onMounted, ref, shallowRef, computed, reactive, onUnmounted} from 'vue';
import { markdownLib } from '@/utils/markdown';
import { copy, isMobile } from '@/utils/util';
import { socketConnect, connect, disconnect, sendMsg, printText, printAddEnd, printAddCon, stopchat } from '@/utils/useSocket1';
import { ElMessage } from 'element-plus';
import { useRoute} from 'vue-router';
const props = defineProps({
  id:{type: Number, default:0}
})
const route = useRoute();
const showTop = ref(true); // 手机端需要用
const answerStatus = ref(0); // 当前按钮状态 0-无发送内容， 1-回答中 2-回答结束 3-中断回答
const emits = defineEmits(['getTalk', 'sendFirst', 'loadingOk', 'loadingIng']);
const sendContent = ref(''); // 需要发送的内容
const againLink = ref(false); // 重连成功
const curLink = reactive({
  status:true, // 当前是否重新连接成功
  token:'', // 当前链接的token
  isSend:false, // 是否需要发送消息
})
// 链接socket 
const markdownHTML = ref(''); // 回答的内容
const printData = ref<string>(``); // 需要打印的全部内容 => 当前的回答内容
const printEnd = ref(0); // 0-未打印or打印结束， 1-打印中, 2-打印结束 or 强制结束
const zbScrollRef = ref(); // 设置滚动条始终在最下面用的

const audioRef = ref(); // 语音
const socketInit = () => {
  socketConnect((res:any)=>{
    if(res.code == 1){
      printData.value+=res.msg; // 本次的数据流的全部数据
      printAddCon(printData.value); // 向打印机中传递最新的数据
      if(printEnd.value != 0) return; // 只有未打印的状态才能执行打印机效果
      audioRef.value?.playFun(1)
      emits('loadingOk')
      printText((msg:string) => {
        markdownHTML.value = `${msg}`;
        zbScrollRef.value?.setData(msg)
      }, (e:number) =>{
        printEnd.value = e;
      });
    }else if(res.code == 2){
      console.log('---本次数据流结束',printData.value)
      printAddEnd(); // 通知打印机 数据流结束
      answerStatus.value = 2;
      printData.value = '';
    }else if(res.code == 0){
      ElMessage.error(res.errmsg)
    }else if(res.code == 6){
      detail.value.beforeMsg = res.msg
    }
  }, (agin:any) =>{
    curLink.status = curLink.token !== agin;
    if(curLink.token !== agin){
      sendMsgToScoket()
      // againLink.value = true;
      console.log('重连成功')
      // if(curLink.status && curLink.isSend){
        
      // }else{
      //   emits('loadingOk')
      // }
    }
    curLink.token = agin;
  })
}
socketInit();



// 发送消息 -- 先断联再建联
const sendMsgFun = (askcon:string) => {
  connect().then(()=>{
    if(!askcon) return ElMessage.error('请输入内容');
    sendContent.value = askcon;
    answerStatus.value = 2; // 结束对话
    printEnd.value = 2; // 打印结束
    audioRef.value?.playFun();
  })
}
// 向scoket中发送消息
const sendMsgToScoket = () => {
  answerStatus.value = 1; // 按钮变成 -- 回答中 -- 状态
  againLink.value = false;
  markdownHTML.value = "";
  printEnd.value = 0;
  sendMsg({msg:sendContent.value, type:3, topic:props.id});
  
}



// 中断对话 + 停止打印效果
const stopTalk = () => {
  stopchat().then(() =>{
    answerStatus.value = 3; // 中断对话
    printEnd.value = 2; // 打印结束
    console.log('中断对话-------------------', answerStatus.value)
  })
}
// 初始化数据
const detail = ref();  // 产品详情
const initData = (data:any) => {
  detail.value = {...data, beforeMsg:''};
}

// 仅共外部清除对话和切换对话调用 -- 不需要重新发送内容
const clear = () => {
  stopchat().then(() =>{
    if(answerStatus.value == 1){ answerStatus.value = 3; }; //
    printEnd.value = 2;
    markdownHTML.value = "";
  })
}
defineExpose({
  initData,
  sendMsgFun,
  clear,
  stopTalk
})
onUnmounted(()=>{
  disconnect();
  printAddEnd(); // 通知打印机 数据流结束
})
</script>
<style lang="scss" scoped>
  $H: calc(var(--vh, 1vh) * 100);
  @import '@/assets/styles/airesult.scss'; // 确保路径正确
  @media only screen and (max-width: 769px){
    .content{height: calc($H - var(--headerH) - 2rem); padding-bottom: 1rem !important;}
    .top.show{margin-bottom: 0.3rem;}
  }
  
</style>